package com.youlai.netty.service.tcp;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * 自定义编码器
 * @author zc
 * @date 2023-01-30 23:44
 */
@Slf4j
public class MyMessageEncoder extends MessageToByteEncoder<String> {

    @Override
    protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out) throws Exception {
        //进行具体的编码处理 这里对字节数组进行打印
        log.info("编码器收到数据:{}",msg);
        MyMessageProtocol protocol = new MyMessageProtocol();
        protocol.setTime(DateTime.now().toStringDefaultTimeZone());
        protocol.setId(RandomUtil.randomInt());
        protocol.setBody(msg);
        //写入并传送数据
        out.writeBytes(JSONUtil.toJsonPrettyStr(protocol).getBytes());
    }
}
